/*
Copyright 2023.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package controllers

import (
	"context"
	"fmt"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	v1 "k8s.io/api/rbac/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/util/retry"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

	"k8s.io/apimachinery/pkg/runtime"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"

	middlewarev1beta1 "github.com/kevinstudy2021/rabbitmq-operator/api/v1beta1"
)

// RabbitmqReconciler reconciles a Rabbitmq object
type RabbitmqReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

//+kubebuilder:rbac:groups=middleware.aliee.com,resources=rabbitmqs,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=middleware.aliee.com,resources=rabbitmqs/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=middleware.aliee.com,resources=rabbitmqs/finalizers,verbs=update
// +kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=services;endpoints,verbs=get;list;watch;create;update;patch;delete

// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the Rabbitmq object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.12.2/pkg/reconcile
func (r *RabbitmqReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	logFormat := log.FromContext(ctx)
	//logFormat := logger.V(3).WithName(req.Name)
	logFormat.Info("====")

	// 首先获取 rabbitmqCluster 实例
	var rabbitmq middlewarev1beta1.Rabbitmq
	if err := r.Get(ctx, req.NamespacedName, &rabbitmq); err != nil {
		// EtcdCluster was deleted，Ignore
		return ctrl.Result{}, client.IgnoreNotFound(err)
	}

	// CreateOrUpdate serviceAccount
	logFormat.Info("Create serviceAccount")
	var sa corev1.ServiceAccount
	for _, v := range rabbitmq.Spec.List {
		if v.Mode == "cluster" {
			sa.Name = rabbitmq.Name
			sa.Namespace = rabbitmq.Namespace
			fmt.Println(v.Name)
			if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
				or, err := ctrl.CreateOrUpdate(ctx, r.Client, &sa, func() error {
					// 调谐必须在这个函数中去实现
					// 判断同名 ServiceAccount 是否存在
					saReq := ctrl.Request{
						NamespacedName: types.NamespacedName{
							Namespace: rabbitmq.Namespace,
							Name:      rabbitmq.Name,
						},
					}
					err := r.Get(ctx, saReq.NamespacedName, &sa)
					if errors.IsNotFound(err) {

						sa.Name = rabbitmq.Name
						sa.Namespace = rabbitmq.Namespace
					} else {
						return err
					}
					return controllerutil.SetControllerReference(&rabbitmq, &sa, r.Scheme)
				})
				logFormat.Info("CreateOrUpdate", "ServiceAccount", or)
				return err
			}); err != nil {
				return ctrl.Result{}, err
			}
		}
	}

	// CreateOrUpdate Role
	logFormat.Info("Create Role")
	var role v1.Role
	for _, v := range rabbitmq.Spec.List {
		role.Name = rabbitmq.Name
		role.Namespace = rabbitmq.Namespace
		if v.Mode == "cluster" {
			if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
				or, err := ctrl.CreateOrUpdate(ctx, r.Client, &role, func() error {
					// 调谐必须在这个函数中去实现
					MutateRole(&v, &role)
					return controllerutil.SetControllerReference(&rabbitmq, &role, r.Scheme)
				})
				logFormat.Info("CreateOrUpdate", "Role", or)
				return err
			}); err != nil {
				return ctrl.Result{}, err
			}
		}
	}

	// CreateOrUpdate RoleBinding
	logFormat.Info("Create RoleBinding")
	var rb v1.RoleBinding
	for _, v := range rabbitmq.Spec.List {
		if v.Mode == "cluster" {
			rb.Namespace = rabbitmq.Namespace
			rb.Name = rabbitmq.Name
			if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
				or, err := ctrl.CreateOrUpdate(ctx, r.Client, &rb, func() error {
					// 调谐必须在这个函数中去实现
					MutateRoleBinding(&v, &rb, &rabbitmq)
					return controllerutil.SetControllerReference(&rabbitmq, &rb, r.Scheme)
				})
				logFormat.Info("CreateOrUpdate", "RoleBinding", or)
				return err
			}); err != nil {
				return ctrl.Result{}, err
			}
		}
	}

	// CreateOrUpdate Service
	logFormat.Info("Create Service")
	var svc corev1.Service
	svc.Namespace = rabbitmq.Namespace
	svc.Name = rabbitmq.Name
	for _, v := range rabbitmq.Spec.List {
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			or, err := ctrl.CreateOrUpdate(ctx, r.Client, &svc, func() error {
				// 调谐必须在这个函数中去实现
				if v.Mode == "cluster" {
					MutateHeadlessSvc(&v, &svc)
				} else {
					MutateNodePortSvc(&v, &svc)
				}
				return controllerutil.SetControllerReference(&rabbitmq, &svc, r.Scheme)
			})
			logFormat.Info("CreateOrUpdate", "Service", or)
			return err
		}); err != nil {
			return ctrl.Result{}, err
		}
	}

	// CreateOrUpdate ConfigMap
	logFormat.Info("Create ConfigMap")
	var cm corev1.ConfigMap
	cm.Name = rabbitmq.Name
	cm.Namespace = rabbitmq.Namespace
	for _, v := range rabbitmq.Spec.List {
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			or, err := ctrl.CreateOrUpdate(ctx, r.Client, &cm, func() error {
				// 调谐必须在这个函数中去实现
				MutateConfigMap(&v, &cm)
				return controllerutil.SetControllerReference(&rabbitmq, &cm, r.Scheme)
			})
			logFormat.Info("CreateOrUpdate", "Service", or)
			return err
		}); err != nil {
			return ctrl.Result{}, err
		}
	}

	// CreateOrUpdate StatefulSet
	logFormat.Info("Create StatefulSet")
	var sts appsv1.StatefulSet
	sts.Name = rabbitmq.Name
	sts.Namespace = rabbitmq.Namespace
	for _, v := range rabbitmq.Spec.List {
		if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
			or, err := ctrl.CreateOrUpdate(ctx, r.Client, &sts, func() error {
				// 调谐必须在这个函数中去实现
				if v.Mode == "cluster" {
					MutateClusterStatefulset(&v, &sts)
				} else if v.Mode == "single" {
					MutateStatefulSet(&v, &sts)
				}
				return controllerutil.SetControllerReference(&rabbitmq, &sts, r.Scheme)
			})
			logFormat.Info("CreateOrUpdate", "StatefulSet", or)
			return err
		}); err != nil {
			logFormat.Info("retryOnConflict find error")
			return ctrl.Result{}, err
		}
	}

	return ctrl.Result{}, nil
}

// SetupWithManager sets up the controller with the Manager.
func (r *RabbitmqReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&middlewarev1beta1.Rabbitmq{}).
		Owns(&appsv1.StatefulSet{}).
		Owns(&corev1.Service{}).
		Complete(r)
}
